﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
//using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
using System.Diagnostics;


namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private SqlConnection conn = new SqlConnection();
        public DataTable dt_drugs;
        public DataTable dt_brand;
        public DataTable dt_suppl;
        public DataTable dt_pharm;
        public DataTable dt_drug_tmp;
        public DataTable dt_rep = new DataTable();
        private const string namechcol = "Флаг";
        private Guid guid;
        private delegate void Deleg();
        private Deleg del;

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn.ConnectionString = @"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True";           
            listBox3.Items.Add("(Все аптеки)");         
            //checkBox3.Checked = true;
            guid = Guid.NewGuid();
            dataGridView1.DataSource = dt_rep.DefaultView;

            if (dt_pharm == null)
            {
                SqlCommand myCommand = conn.CreateCommand();
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.CommandText = @"pas_PharmSel";
                if (conn.State == ConnectionState.Closed) conn.Open();
                dt_pharm = new DataTable();
                dt_pharm.Load(myCommand.ExecuteReader());
                foreach (DataColumn dc in dt_pharm.Columns)
                {
                    if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                    else dc.ReadOnly = false;
                }
                conn.Close();
            }
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            //if (checkBox3.Checked) listBox3.Enabled = true;
            //else listBox3.Enabled = false;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            dt_rep.Clear();
            del = new Deleg(CreateRep);
            this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            panel1.Enabled = false;
            dataGridView1.Enabled = false;
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_rep.DefaultView));
        }

        private void CreateRep()
        {
            if (conn.State == ConnectionState.Closed) conn.Open();
            try
            {
                SqlCommand myCommand = conn.CreateCommand();
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.CommandText = @"pas_GuidNatureCodeINS";
                myCommand.Parameters.Add("@guid", SqlDbType.UniqueIdentifier);
                myCommand.Parameters.Add("@code", SqlDbType.Int);
                myCommand.Parameters.Add("@del", SqlDbType.Bit);
                myCommand.Parameters.Add("@nature", SqlDbType.VarChar, 5);

                if (conn.State == ConnectionState.Closed) conn.Open();

                myCommand.Parameters["@guid"].Value = guid;
                myCommand.Parameters["@code"].Value = null;
                myCommand.Parameters["@del"].Value = true;
                myCommand.Parameters["@nature"].Value = null;
                myCommand.ExecuteNonQuery();

                guid = Guid.NewGuid();

                if (dt_pharm != null)
                {
                    if (listBox3.Items[0].ToString() == "(Все аптеки)")
                    {
                        foreach (DataRow dr in dt_pharm.Rows)
                        {
                            myCommand.Parameters["@guid"].Value = guid;
                            myCommand.Parameters["@code"].Value = Convert.ToInt32(dr["Код"]); ;
                            myCommand.Parameters["@del"].Value = false;
                            myCommand.Parameters["@nature"].Value = "pharm";
                            myCommand.ExecuteNonQuery();
                        }
                    }
                    else
                        foreach (DataRow dr in dt_pharm.Rows)
                            if (Convert.ToBoolean(dr[namechcol]) == true)
                            {
                                myCommand.Parameters["@guid"].Value = guid;
                                myCommand.Parameters["@code"].Value = Convert.ToInt32(dr["Код"]); ;
                                myCommand.Parameters["@del"].Value = false;
                                myCommand.Parameters["@nature"].Value = "pharm";
                                myCommand.ExecuteNonQuery();
                            }
                }
                dt_rep.Clear();
                dt_rep.Load(RepProc(guid));
                //dataGridView1.DataSource = dt_rep.DefaultView;

                myCommand.Parameters["@guid"].Value = guid;
                myCommand.Parameters["@code"].Value = null;
                myCommand.Parameters["@del"].Value = true;
                myCommand.Parameters["@nature"].Value = null;
                myCommand.ExecuteNonQuery();

                //conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                //conn.Close();
            }
        }

        private SqlDataReader RepProc(Guid id)
        {
            SqlConnection con = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=CountDW;Integrated Security=True");
            con.Open();
            SqlCommand sqlcom = con.CreateCommand();
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.CommandText = @"pas_InOutPharmCountDaysSel";
            sqlcom.CommandTimeout = 300;

            sqlcom.Parameters.Add("@guid", SqlDbType.UniqueIdentifier);
            sqlcom.Parameters["@guid"].Value = id;

            sqlcom.Parameters.Add("@countd", SqlDbType.Int);
            sqlcom.Parameters["@countd"].Value = Convert.ToInt32(textBox1.Text);

            return sqlcom.ExecuteReader();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                PharmFilter.PharmFilter f3 = new PharmFilter.PharmFilter();


                f3.namechcol = namechcol;
                f3.Text = "Фильтр по аптекам";
                f3.sortcoumn = "Аптека";
                f3.dataGridView1.DataSource = dt_pharm.DefaultView;
                f3.ShowDialog();
                listBox3.Items.Clear();
                foreach (DataRow dr in dt_pharm.Rows)
                {
                    if (Convert.ToBoolean(dr[namechcol]) == true) listBox3.Items.Add(dr[f3.sortcoumn]);
                }
                if (listBox3.Items.Count == 0) listBox3.Items.Add("(Все аптеки)");
                f3.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void button5_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "контроль посетителей";
            sfd.Filter = "Файл CSV | *.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {   
                SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, true);
            }
        }

        public static bool SaveDGVToCSVfile(string filename, DataGridView table, bool openInExcel)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false, Encoding.Unicode);

                List<int> col_n = new List<int>();
                foreach (DataGridViewColumn col in table.Columns)
                    if (col.Visible)
                    {
                        sw.Write(col.HeaderText + "\t");
                        col_n.Add(col.Index);
                    }
                sw.WriteLine();
                int x = table.RowCount;
                if (table.AllowUserToAddRows) x--;

                for (int i = 0; i < x; i++)
                {
                    for (int y = 0; y < col_n.Count; y++)
                        sw.Write(table[col_n[y], i].Value + "\t");
                    sw.Write(" \r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (openInExcel)
            {
                try
                {
                    Process newProc = Process.Start("excel.exe", "\"" + filename + "\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            return true;
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsDigit(e.KeyChar)) && !((e.KeyChar == '.') && (textBox1.Text.IndexOf(".") == -1) && (textBox1.Text.Length != 0)))
            {
                if (e.KeyChar != (char)Keys.Back)
                {
                    e.Handled = true;
                }
            }
        }

    }
}
